package com.cloudkinto.service.replacement.impl;

import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloudkinto.common.DicBusinessItemConstant;
import com.cloudkinto.common.constant.SysConstant;
import com.cloudkinto.common.exception.BizException;
import com.cloudkinto.common.exception.BizExceptionI18;
import com.cloudkinto.common.utils.ExcelUtils;
import com.cloudkinto.common.utils.OrderCodeUtil;
import com.cloudkinto.common.utils.TimeUtils;
import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;
import com.cloudkinto.dao.*;
import com.cloudkinto.entity.OrderOutputDo;
import com.cloudkinto.entity.OrderOutputProductDo;
import com.cloudkinto.entity.ProductInfoDo;
import com.cloudkinto.entity.ReplacementDo;
import com.cloudkinto.service.file.FileService;
import com.cloudkinto.service.replacement.ReplacementService;
import com.cloudkinto.service.replacement.impl.vo.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.function.Consumer;

/**
 * @author fanp
 * @version v1.0.0
 * @Description :
 * @Create on : 2021/2/20 14:43
 **/
@Service
@Transactional(rollbackFor = Exception.class)//事务回滚
public class ReplacementServiceImpl extends ServiceImpl<ReplacementDao, ReplacementDo> implements ReplacementService {
    @Autowired
    ReplacementDao dao;
    @Autowired
    OrderOutputDao orderOutputDao;
    @Autowired
    private OrderOutputProductDao productDao;
    @Autowired
    private ProductInfoDao productInfoDao;
    @Autowired
    private FileService fileService;
    @Autowired
    private StorageDao storageDao;


    //将主表中的某些信息带过来
    @Override
    public SingleResult addInit(Long outputId) {
        //新增加一个无关配件
        if (outputId.equals(-1L)) {
            return SingleResult.success();
        }
        Map<String, Object> map = new HashMap<>();
        OrderOutputDo orderOutputDo = orderOutputDao.selectById(outputId);
        if (orderOutputDo == null) {
            throw new BizExceptionI18(SysConstant.Order_Replace_NotExist);
        }
        ReplacementAddInitReq replacementAddInitReq = new ReplacementAddInitReq();
        BeanUtils.copyProperties(orderOutputDo, replacementAddInitReq);
        //对于CommoditySku 为空进行处理  补发表中需要存储
        if (StringUtils.isBlank(orderOutputDo.getCommoditySku())) {
            QueryWrapper wrapper1 = new QueryWrapper();
            wrapper1.eq("order_id", orderOutputDo.getId());
            List<OrderOutputProductDo> productList = productDao.selectList(wrapper1);
            StringBuilder sb = new StringBuilder();
            for (OrderOutputProductDo productDo : productList) {
                if (sb.length() > 0) {
                    sb.append(",");
                }
                sb.append(productInfoDao.selectById(productDo.getProductId()).getCommoditySku());
            }
            replacementAddInitReq.setCommoditySku(sb.toString());
        }
        map.put("fatherInformation", replacementAddInitReq);
        //前端无需显示的参数
        ReplacementAddInitThreeReq replacementAddInitThreeReq = new ReplacementAddInitThreeReq();
        replacementAddInitThreeReq.setOutputCompanyId(orderOutputDo.getCompanyId());
        replacementAddInitThreeReq.setOutputShopId(orderOutputDo.getShopId());
        //所有订单从GLC 发货
        replacementAddInitThreeReq.setOutputStorageId(13L);
//        replacementAddInitThreeReq.setOutputStorageId(orderOutputDo.getStorageId());
//        StorageDo storageDo = storageDao.selectById(orderOutputDo.getStorageId());
        replacementAddInitThreeReq.setOutputPostCode(orderOutputDo.getPostCode());
        map.put("remainingInformation", replacementAddInitThreeReq);
        //补发信息  可能不存在信息(遍历出来不存在就不显示)  可能多个
        LambdaQueryWrapper<ReplacementDo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ReplacementDo::getOutputOrderId, outputId);
        List<ReplacementDo> replacementDos = dao.selectList(wrapper);
        //为空跳过
        if (replacementDos.size() < 1) {
            return SingleResult.success(map);
        }
        List<ReplacementAddInitTwoReq> list = new ArrayList();
        for (ReplacementDo replacementDo : replacementDos) {
            ReplacementAddInitTwoReq replacementAddInitTwoReq = new ReplacementAddInitTwoReq();
            BeanUtils.copyProperties(replacementDo, replacementAddInitTwoReq);
            //获取图片链接
            replacementAddInitTwoReq.setUrl(fileService.getFilePath(replacementDo.getFileId()));
            list.add(replacementAddInitTwoReq);
            map.put("sonInformation", list);
        }
        return SingleResult.success(map);
    }

    //添加
    @Override
    public SingleResult add(Long currentUserId, ReplacementAddReq addReq, Long companyId) {
        if (addReq.getReplacementAddInitTwoReqList().size() < 1) {
            return SingleResult.success();
        }
        for (ReplacementAddInitTwoReq replacementAddInitTwoReq : addReq.getReplacementAddInitTwoReqList()) {
            ReplacementDo replacementDo = new ReplacementDo();
            replacementDo.setOutputOrderId(addReq.getReplacementAddInitReq().getId());
            replacementDo.setOutputOrderNo(addReq.getReplacementAddInitReq().getOrderNo());
            replacementDo.setOutputArea(addReq.getReplacementAddInitReq().getArea());
            replacementDo.setNeedPhoto(addReq.getReplacementAddInitReq().getNeedPhoto());
            replacementDo.setOrderType(addReq.getReplacementAddInitReq().getOrderType());
            replacementDo.setOutputReceiverName(addReq.getReplacementAddInitReq().getReceiverName());
            replacementDo.setOutputTelPhone(addReq.getReplacementAddInitReq().getTelPhone());
            replacementDo.setOutputAddress(addReq.getReplacementAddInitReq().getAddress());
            replacementDo.setOutputPostCode(addReq.getReplacementAddInitReq().getPostCode());
            replacementDo.setOutputCommoditySku(addReq.getReplacementAddInitReq().getCommoditySku());
            if (StringUtils.isNotBlank(addReq.getReplacementAddInitReq().getCod())) {
                int cod = 0;
                try {
                    cod = Integer.parseInt(addReq.getReplacementAddInitReq().getCod());
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
                replacementDo.setCod(cod);
            }
            if (replacementAddInitTwoReq.getFileId() == null) {
                replacementAddInitTwoReq.setFileId(-1L);
            }
            if (replacementAddInitTwoReq.getNumber() == null || replacementAddInitTwoReq.getNumber() < 1) {
                throw new BizExceptionI18(SysConstant.PLS_INPUT_SKU_COUNT);
            }
            BeanUtils.copyProperties(replacementAddInitTwoReq, replacementDo);
            BeanUtils.copyProperties(addReq.getReplacementAddInitThreeReq(), replacementDo);
            if (!replacementAddInitTwoReq.getFileId().equals(-1L)) {
                fileService.uploadFile(replacementAddInitTwoReq.getFileId());
            }
            LambdaQueryWrapper<ProductInfoDo> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ProductInfoDo::getCompanyId, companyId);
            wrapper.eq(ProductInfoDo::getCommoditySku, replacementDo.getOutputCommoditySku());
            if (replacementDo.getSize() == null || replacementDo.getSize() == 1) {
                replacementDo.setTrackId(DicBusinessItemConstant.sagawaExpress);
            }
            ProductInfoDo productInfoDo = productInfoDao.selectOne(wrapper);
            if (productInfoDo == null)
                throw new BizExceptionI18(SysConstant.Product_NotFound, replacementDo.getOutputCommoditySku());
            replacementDo.setProductInfoId(productInfoDo.getId());
            replacementDo.setCreateTime(new Date());
            replacementDo.setCreateBy(currentUserId);
            if (replacementDo.getOutputCompanyId() == null) {
                replacementDo.setOutputCompanyId(companyId);
            }
            dao.insert(replacementDo);
            String stringCode = OrderCodeUtil.getOrderReplaceNumber(replacementDo.getId());
            replacementDo.setOrderNo(stringCode);
            if (addReq.getReplacementAddInitReq().getId() == null || addReq.getReplacementAddInitReq().getId() == 0) {
                replacementDo.setOutputOrderId(replacementDo.getId());
            }
            updateById(replacementDo);
        }
        return SingleResult.success();
    }

    @Override
    public SingleResult updateR(Long currentUserId, ReplacementUpdateReq replacementUpdateReq) {
        ReplacementDo replacementDo = dao.selectById(replacementUpdateReq.getReplacementAddInitTwoReq().getId());
        if (!replacementDo.getStatus().equals(0)) {
            throw new BizExceptionI18(SysConstant.Order_Replace_Update_Error);
        }
        long fileId = replacementDo.getFileId();
        replacementDo.setOutputOrderId(replacementUpdateReq.getReplacementAddInitReq().getId());
        replacementDo.setOutputOrderNo(replacementUpdateReq.getReplacementAddInitReq().getOrderNo());
        replacementDo.setOutputArea(replacementUpdateReq.getReplacementAddInitReq().getArea());
        replacementDo.setNeedPhoto(replacementUpdateReq.getReplacementAddInitReq().getNeedPhoto());
        replacementDo.setOrderType(replacementUpdateReq.getReplacementAddInitReq().getOrderType());
        replacementDo.setOutputReceiverName(replacementUpdateReq.getReplacementAddInitReq().getReceiverName());
        replacementDo.setOutputTelPhone(replacementUpdateReq.getReplacementAddInitReq().getTelPhone());
        replacementDo.setOutputAddress(replacementUpdateReq.getReplacementAddInitReq().getAddress());
        replacementDo.setOutputPostCode(replacementUpdateReq.getReplacementAddInitReq().getPostCode());
        replacementDo.setOutputCommoditySku(replacementUpdateReq.getReplacementAddInitReq().getCommoditySku());
        if (StringUtils.isNotBlank(replacementUpdateReq.getReplacementAddInitReq().getCod())) {
            int cod = 0;
            try {
                cod = Integer.parseInt(replacementUpdateReq.getReplacementAddInitReq().getCod());
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
            replacementDo.setCod(cod);
        }

        BeanUtils.copyProperties(replacementUpdateReq.getReplacementAddInitTwoReq(), replacementDo);
        BeanUtils.copyProperties(replacementUpdateReq.getReplacementAddInitThreeReq(), replacementDo);
        replacementDo.setUpdateTime(new Date());
        replacementDo.setUpdateBy(currentUserId);
        //图片是否要修改
        if (fileId != replacementUpdateReq.getReplacementAddInitTwoReq().getFileId()) {
            fileService.deleteFile(fileId);
            fileService.uploadFile2(replacementUpdateReq.getReplacementAddInitTwoReq().getFileId(), fileId);
        }
        LambdaQueryWrapper<ProductInfoDo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProductInfoDo::getCompanyId, replacementDo.getOutputCompanyId());
        wrapper.eq(ProductInfoDo::getCommoditySku, replacementDo.getOutputCommoditySku());
        if (replacementDo.getSize() == null || replacementDo.getSize() == 1) {
            replacementDo.setTrackId(DicBusinessItemConstant.sagawaExpress);
        }
        ProductInfoDo productInfoDo = productInfoDao.selectOne(wrapper);
        if (productInfoDo == null)
            throw new BizExceptionI18(SysConstant.Product_NotFound, replacementDo.getOutputCommoditySku());
        replacementDo.setProductInfoId(productInfoDo.getId());
        dao.updateById(replacementDo);
        return SingleResult.success();
    }

    //删除
    @Override
    public SingleResult delete(Long currentUserId, Long id) {
        ReplacementDo replacementDo = dao.selectById(id);
        if (replacementDo == null) {
            throw new BizExceptionI18(SysConstant.Order_Replace_Notfound);
        }
        // 0是已下单 但未有其他处理
        if (!replacementDo.getStatus().equals(0)) {
            throw new BizExceptionI18(SysConstant.Order_Replace_Delete_Error);
        }
        fileService.deleteFile(replacementDo.getFileId());
        replacementDo.setDeleteBy(currentUserId);
        replacementDo.setDeleteTime(new Date());
        dao.deleteById(id);
        return SingleResult.success();
    }

    @Override
    public PageResult getListPage(Map<String, String> map) {
        QueryWrapper<ReplacementDo> wrapper = queryBuild(map);
        IPage<ReplacementDo> page = pageInit(map);
        page = this.page(page, wrapper);
        List<ReplacementPageRes> resList = handlerListAfter(page.getRecords());
        PageResult result = new PageResult(resList, (int) page.getCurrent(), (int) page.getSize(), (int) page.getTotal(), (int) page.getPages());
        return result;
    }

    private QueryWrapper<ReplacementDo> queryBuild(Map<String, String> map) {
        QueryWrapper<ReplacementDo> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(map.get("keyword"))) {
            String keyword = map.get("keyword").replaceAll(" ", "").replaceAll("\\n", "");
            wrapper.and(new Consumer<QueryWrapper<ReplacementDo>>() {
                @Override
                public void accept(QueryWrapper<ReplacementDo> replacementDoQueryWrapper) {
                    replacementDoQueryWrapper.like("output_order_no", keyword)
                            .or().like("order_no", keyword)
                            .or().like("output_commodity_sku", keyword)
                            .or().like("commodity_sku", keyword)
                            .or().like("output_receiver_name", keyword)
                            .or().like("product_name", keyword);
                }
            });
        }
        if (StringUtils.isNotBlank(map.get("orderNo"))) {
            wrapper.eq("order_no", map.get("orderNo"));
        }
        if (StringUtils.isNotBlank(map.get("outputShopId"))) {
            wrapper.eq("output_shop_id", map.get("outputShopId"));
        }
        if (StringUtils.isNotBlank(map.get("outputStorageId"))) {
            wrapper.eq("output_storage_id", Integer.parseInt(map.get("outputStorageId")));
        }
        if (StringUtils.isNotBlank(map.get("status"))) {
            wrapper.eq("status", Integer.parseInt(map.get("status")));
        }
        if (StringUtils.isNotBlank(map.get("companyId"))) {
            wrapper.eq("output_company_id", map.get("companyId"));
        }
        if (StringUtils.isNotBlank(map.get("startDate"))) {
            wrapper.ge("create_time", map.get("startDate"));
        }
        if (StringUtils.isNotBlank(map.get("endDate"))) {
            wrapper.le("create_time", map.get("endDate"));
        }
        wrapper.orderByDesc("id");
        return wrapper;
    }

    private IPage<ReplacementDo> pageInit(Map<String, String> map) {
        IPage<ReplacementDo> page = new Page();
        page.setSize(StringUtils.isNotBlank(map.get("pageSize")) ? Long.parseLong(map.get("pageSize")) : 10);
        page.setCurrent(StringUtils.isNotBlank(map.get("current")) ? Long.parseLong(map.get("current")) : 1);
        return page;
    }

    //查询分页列表之后对列表数据的处理
    private List<ReplacementPageRes> handlerListAfter(List<ReplacementDo> list) {
        List<ReplacementPageRes> result = new ArrayList<>();
        if (list.size() > 0) {
            for (ReplacementDo replacementDo : list) {
                ReplacementPageRes replacementPageRes = new ReplacementPageRes();
                BeanUtils.copyProperties(replacementDo, replacementPageRes);
                replacementPageRes.setCod(replacementDo.getCod());
                replacementPageRes.setStorageName(storageDao.selectById(replacementDo.getOutputStorageId()).getStorageName());
                switch (replacementPageRes.getStatus()) {
                    case 1:
                        replacementPageRes.setStatusName("已打单");
                        break;
                    case 2:
                        replacementPageRes.setStatusName("已发货");
                        break;
                    default:
                        replacementPageRes.setStatusName("已审核");
                        break;
                }
                if (replacementDo.getFileId() != -1L) {
                    replacementPageRes.setUrl(fileService.getFilePath(replacementDo.getFileId()));
                }
                if (replacementDo.getConfirmFileId() != null && replacementDo.getConfirmFileId() != -1L) {
                    replacementPageRes.setConfirmFileUrl(fileService.getFilePath(replacementDo.getConfirmFileId()));
                }
                replacementPageRes.setSendDate(TimeUtils.formatDate(replacementDo.getCreateTime()));
                result.add(replacementPageRes);
            }
        }
        return result;
    }


    //导出
    @Override
    public void exportExcel(List<Long> ids, HttpServletResponse response) {
        if (ids.size() < 1) {
            throw new BizExceptionI18(SysConstant.Error_PleChoose);
        }
        List<ReplacementDo> replacementDos = dao.selectBatchIds(ids);
        List<ReplacementExportVo> replacementExportVos = new ArrayList<>();
        for (ReplacementDo replacementDo : replacementDos) {
            ReplacementExportVo replacementExportVo = new ReplacementExportVo();
            BeanUtils.copyProperties(replacementDo, replacementExportVo);
            replacementExportVos.add(replacementExportVo);
        }
        //打印
        try {
            ExcelUtils.exportExcel(replacementExportVos, ReplacementExportVo.class, "补发信息单", new ExportParams(), response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void confirmPhone(Long id, Long userId) {
        ReplacementDo et = dao.selectById(id);
        if (et == null) {
            throw new BizException(SysConstant.No_Data);
        }
        if (et.getNeedPhoto() != 2) {
            throw new BizException(SysConstant.OrderRepair_Status_Error);
        }
        et.setNeedPhoto(3);
        dao.updateById(et);

    }
}
